/**
 * useRequest 封装
 * @Author: linzy
 * @Date: 2022-05-09
 * 大致的使用跟useRequest一致 options传参有些许不同
 * 默认配置
 * options传参：
 *  1.  如果传refreshDeps 或者ready为真 则为表格的请求 则为自动请求，其他为手动请求
 *  2.  如果options传入refresh 表明请求完成后需要执行refresh操作
 *      refresh 可以是函数数组 function[] 也可以是单个函数
 *  3.  如果options传入onSuccess 则会替换默认的onSuccess 不会执行refresh
 * @description useRequest请求封装
 * @function useRequest
 * @param {function} service - 请求方法
 * @param {object} options - 请求参数
 * @example
const { data: tableData = {}, loading, refresh } = useRequest(
  ()=>api.getTableData(tableForm),
  {refreshDeps: [tableForm]}
);
const { run: del, loading: delLoading } = useRequest(api.del, {refresh});
const { data: detail = {} } = useRequest(()=>api.getDetail({id}), {
  ready: true
});
 */
import { useRequest } from "ahooks";
import { setDefaultAttrs } from "@/hooks/tools";

export default (service, options = {}) => {
  setDefaultAttrs(options, {
    debounceWait: 50,
    debounceMaxWait: 1000,
    manual: options.refreshDeps || options.ready ? false : true,
    onSuccess(res) {
      if (options.refresh && (res?.code === 0 || res === true)) {
        if (Array.isArray(options.refresh)) {
          options.refresh.forEach(item => item());
        } else {
          if (options.delay) {
            setTimeout(() => {
              options.refresh();
            }, options.delay);
          } else {
            options.refresh();
          }
        }
      }
    }
  });
  const request = useRequest(service, options);
  request.run = request.runAsync;
  request.refresh = request.refreshAsync;
  return request;
};
